
from flask import Flask, render_template, request
from flask import jsonify
import json
import os
# from PredictTCL_main.Predict import PredictTCL
from PredictTCL_main.Predict_1fold import PredictTCL
from API.get_list_from_Orthanc import get_list_from_Orthanc
from database.get_dicom_from_Orthanc import get_dicom_from_Orthanc
from login import model_login_page

from database.TCL_mysql import TCL_update
from database.delete_mysql import delete
from database.update_mysql import update
from database.NormalQuery import normal_query

from database.TopQuery import top_query
from database.uploadDicom import UploadFile,SaveFile
from database.save_upload_ZIP import upload2orthanc,SaveFile
# 在此处选择是否保存mask
from API.segmentation_save_mask import segmentation_api
# from API.segmentation import segmentation_api
from Flask_run import app,db

app.register_blueprint(model_login_page,url_prefix='/login')


@app.route("/get_list_from_Orthanc", methods=["GET", "POST"])
def get_list():
    if request.method == "GET":
        data = request.get_data()
        data = json.loads(data)
        patient_id = data['patient_id']
        study_id = data['study_id'] 
        study_list=get_list_from_Orthanc(patient_id,study_id) # 这里的study_list需要返回吗？
        print(study_list) 
    return jsonify(status="success")


@app.route("/get_dicom_from_Orthanc", methods=["GET", "POST"])
def get_dicom():
    if request.method == "GET":
        data = request.get_data()
        data = json.loads(data)
        study_id = data['study_id'] 
        save_path=get_dicom_from_Orthanc(study_id) # 这里的study_list需要返回吗？
        print(save_path)
    return jsonify(status="success",save_path=save_path)


@app.route("/Predict", methods=["GET", "POST"])
def Predict():
    if request.method == "POST":
        # 获取前端的数据和study id
        data=request.get_json()
        study_id = data.get("study_id", None)
        if study_id is None:
            print(f"error")

        # 根据study id从orthanc数据库中获取需要分析的图像，并返回保存的路径
        save_path=get_dicom_from_Orthanc(study_id) 
        # 根据图像路径，调用分割算法
        state = segmentation_api(save_path, study_id)
        print(state)
        # 分割完成后，根据study id定位到需要进行预测的数据，进行预测
        if state == 20000:
            UploadFile(f"../segmentation_saved/{study_id}_segmentation.dcm")
            result_list=PredictTCL(study_id)
            TCL_update(study_id,result_list[0],result_list[1])
            return jsonify(status=state,result=result_list, code=20000)
        if state == 10000:   # T1 模态缺失
            return jsonify(status=state, code=20000)
        if state == 5000:    # 病例无肿瘤或未分割出肿瘤
            return jsonify(status=state, code=20000)
      
      
# @app.route('/Query',methods = ["GET", "POST"])
# def topQuery():
#     if request.method == "GET":
#         data=request.get_json()
#         find_state = data['find_state']
#         name = data['name']
#         check_date1 = data['check_date1']
#         check_date2 = data['check_date2']
#         operation_date1 = data['operation_date1']
#         operation_date2 = data['operation_date2']
#         p_sub = data['p_sub']
#         p_invasive = data['p_invasive']
#         p_level = data['p_level']
        
#         condition = {
#             "find_state": find_state ,
#             "name": name,
#             "check_date1": check_date1 ,
#             "check_date2": check_date2 ,
#             "operation_date1": operation_date1,  # 检查日期 小
#             "operation_date2": operation_date2,  # 检查日期 大
#             "p_sub": p_sub,  # 病理亚型
#             "p_invasive": p_invasive,  # 病理结果是否脑侵袭
#             "p_level": p_level  # 病理结果是否脑侵袭
#         }
#         result=top_query(condition)
#         return jsonify(status="success",result=result)         

@app.route('/Query',methods = ["GET", "POST"])
def topQuery():
    if request.method == "GET":
        # 这一块要传入六个参数给查询函数
        find_state=request.args.get("find_state", "")
        name=request.args.get("name", "")
        check_date1=request.args.get("check_date1", "")
        check_date2=request.args.get("check_date2", "")
        op_date1=request.args.get("op_date1", "")
        op_date2=request.args.get("op_date2", "")

        print('check_data1',check_date1)
        print('check_data2',check_date2)

        print('op_data1',op_date1)
        print('op_data2',op_date2)

        p_sub=request.args.get("p_sub", "")
        p_invasive=request.args.get("p_invasive", "")
        p_level=request.args.get("p_level", "")

        condition = {
            "find_state": find_state,
            "name": name,
            "check_date1": check_date1,
            "check_date2": check_date2,
            "operation_date1":op_date1,
            "operation_date2":op_date2,
            "p_sub": p_sub,
            "p_invasive": p_invasive,    
            "p_level": p_level    
        }  
       
        print('_____________ ______',condition)
        result=top_query(condition)
        print(result)
        return jsonify(status="success",result=result)


@app.route('/NormalQuery',methods = ["GET", "POST"])
def NormalQuery():
    if request.method == "GET":
        find_state=request.args.get("find_state")
        name=request.args.get("name")
        check_date=request.args.get("check_date")
        condition = {
            "find_state": find_state,
            "name": name,
            "check_date": check_date
        }  
        result=normal_query(condition)
        return jsonify(status="success",result=result)     

          
@app.route("/uploadfile",methods=["POST"])
def image_upload():
   #当以post方式提交数据时
  if request.method == 'POST':
      file = request.files['file']#将上传的文件赋予file
    #   print(file.filename)
      # 保存到本地并归类
      path=SaveFile(file,file.filename)
    #   print('finish save')
      state=upload2orthanc(path)
      if state == 3000:    # 文件夹为空时
        return jsonify(status=state, code=3000)
      else:    
        return jsonify(status="success")
      


  
@app.route("/Mri_delete", methods=["GET", "POST"])
def Mri_delete():
    if request.method == "GET":
        study_id=request.args.get('study_id')
        print(study_id)
        status=delete(study_id)
        if status==1:
            code = 20000
        else:
            code = 201
        return jsonify(status=status, code=code)

@app.route("/Mri_update", methods=["GET", "POST"])
def Mri_update():
    if request.method == "POST":
        data=request.get_json()
        print(data['data'])
        status=update(data['data'])
        if status==1:
            code = 20000
        else:
            code = 201
        return jsonify(status=status, code=code)
    

if __name__ == "__main__":
    app.run(host="127.0.0.1", port=5051, debug=True)
    
    
# 这个接口可以不用，已经放在预测里了
# @app.route("/TCL_update", methods=["GET", "POST"])
# def tcl_update():
#     if request.method == "GET":
#         data=request.get_json()
#         study_id=data['study_id']
#         inv_pred=data['inv_pred']
#         men_pred=data['men_pred']
#         TCL_update(study_id,inv_pred,men_pred)
#         return jsonify(status="success")

      
# @app.route("/upload2Orthanc", methods=["GET", "POST"])
# def dicom_upload():
#     if request.method == "GET":
#         data=request.get_json()
#         url=data['url']
#         username=data['username']
#         password=data['password']
#         data_path=data['data_path']
#         upload2orthanc(url,username,password,data_path)
        
#         return jsonify(status="success")

    
# 这个接口可以不用，已经放在uploadDicom里了    这个接口还没写完，应该很多bug
# @app.route('/addmri',methods = ["GET", "POST"])
# def addmri():
#     data=request.get_json()
#     pid = data['Study_id']
#     fid = data['fid']
#     borndate = data['borndate']
#     checkdate = data['checkdate']
#     name = data['PatientName']
#     sex = data['sex']
#     # 根据检查病人是否存在
    
#     patient = Patient.query.filter(Patient.pid == pid).first()
#     if patient is None:
#         #不存在则添加
#         try:
#             newpatient = Patient(name,sex,pid,borndate)
#             db.session.add(newpatient)
#             db.session.commit()
#         except:
#             msg = Message(501,{},"数据库写入异常")
#             return msg.response()
#         else:
#             patient = Patient.query.filter(Patient.pid == pid).first()
#     #添加mri记录
#     try:
#         # 检查mri时候存在，不过没必要数据库设置F号唯一即可，重复插入会报错
#         newmri = Mri(fid,patient.id,checkdate)
#         db.session.add(newmri)
#         db.session.commit()
#     except:
#         msg = Message(501,{},"数据库写入异常")
#         return msg.response()
#     else:
#         msg = Message(200,{},"ok")
#         return msg.response()